# -*- coding:utf-8 -*-
import os,sys
import re
import traceback
import copy
import time
from collections import deque
import numpy
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, os.pardir))
import supeanut_config
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
from CommonLib.mylog import mylog
from CommonLib.StockTool import StockTool
from BasicTool import BasicTool
from ExrightsTool import ExrightsTool
from TrendRecog import TrendRecog
from KlineRecog import KlineRecog
from SellStrategy import SellStrategy
from CommonLib.StockTool import StockTool

'''
作者：supeanut
创建时间：2016-xx-xx xx:xx:xx
功能描述：
相关配置：
	supeanut_config.XXX
历史改动：
	2016-xx-xx: xxxxxx
'''
class Strategy:
	def __init__(self):
		# Recog注册
		KlineRecogObj = KlineRecog()
		TrendRecogObj = TrendRecog()
		SellStrategyObj = SellStrategy()
		self.funcObjMap = {"hongSanBing": KlineRecogObj, "sanWuYa": KlineRecogObj, "zhiYingSun":SellStrategyObj,\
						   "pingTai": TrendRecogObj, "pricePos": TrendRecogObj, "warmUpShoot":TrendRecogObj,\
						   "priceVolMaUp": TrendRecogObj, "priceVolCoor":TrendRecogObj,"redGreenRatio":TrendRecogObj,\
						   "yinBaoYang": KlineRecogObj, "KDJGoldCross": TrendRecogObj, "ma3duoTouPaiLie": TrendRecogObj,\
						   "RedAndVolBig": TrendRecogObj, }

	# 动态执行识别函数
	def runRecog(self, func_name, param_dict):
		return getattr(self.funcObjMap[func_name], func_name)(**param_dict)

	# 可外挂限制
	def getParamRange(self, func_name, param_limit_dict):
		defaultParamRange = getattr(self.funcObjMap[func_name], "getParamRange")(func_name)
		if param_limit_dict is None:
			return defaultParamRange
		for limit_name, limit_range in param_limit_dict.items():
			defaultParamRange[limit_name] = limit_range
		return defaultParamRange

	# 默认取最小的值
	def initParam(self, paramRange):
		initParamDict = {}
		for param_name, param_range in paramRange.items():
			initParamDict[param_name] = param_range[0][0]
		return initParamDict

	# buy_strategy_order: 买入策略组所有参数的顺序
	def createStratey(self, buy_names, sell_names, paramLimit):
		# 买入策略组, 交集生效
		buy_strategy = {}
		buy_strategy_order = {'nameList':[], 'paramNameListDict':{}}
		for buy_name in buy_names:
			paramRange = self.getParamRange(buy_name, paramLimit['buy'].get(buy_name))
			curParam = self.initParam(paramRange)
			buy_strategy[buy_name] = {"paramRange": paramRange, "curParam": curParam}
			buy_strategy_order['nameList'].append(buy_name)
			buy_strategy_order['paramNameListDict'][buy_name] = list(curParam)
		# 卖出策略组，最近生效
		sell_strategy = {}
		sell_strategy_order = {'nameList':[], 'paramNameListDict':{}}
		for sell_name in sell_names:
			paramRange = self.getParamRange(sell_name, paramLimit['sell'].get(sell_name))
			curParam = self.initParam(paramRange)
			sell_strategy[sell_name]  = {"paramRange": paramRange, "curParam": curParam}
			sell_strategy_order['nameList'].append(sell_name)
			sell_strategy_order['paramNameListDict'][sell_name] = list(curParam)
		return buy_strategy, sell_strategy, buy_strategy_order, sell_strategy_order


	# 输入buy_strategy / sell_strategy
	# 按顺序获取下一个参数，设置curParam
	# 到底则返回False，否则True
	def nextParam(self, strategy, strategy_order):
		# 计算总参数个数
		allParamLen = 0
		for strategy_name in strategy_order['nameList']:
			for param_name in strategy_order['paramNameListDict'][strategy_name]:
				allParamLen += 1
		# 遍历子策略
		allParamIndex = 0
		jinwei = False
		for strategy_name in strategy_order['nameList']:
			paramRange = strategy[strategy_name]['paramRange']
			curParam = strategy[strategy_name]['curParam']
			# 遍历子策略的参数
			for param_name in strategy_order['paramNameListDict'][strategy_name]:
				allParamIndex += 1
				param_name_range = paramRange[param_name]
				param_name_cur = curParam[param_name]
				param_name_new = param_name_cur + param_name_range[1]
				# 未达上限
				if param_name_new <= param_name_range[0][1]:
					strategy[strategy_name]['curParam'][param_name] = param_name_new
					# 设置跳出双层循环
					jinwei = True
					break
				# 达到上限，需要继续向后探索搜索空间
				if allParamIndex == allParamLen:
					return False
			if jinwei is True:
				break
		# 在allParamIndex排序之前的所有参数置range-low
		curParamIndex = 0
		for strategy_name in strategy_order['nameList']:
			paramRange = strategy[strategy_name]['paramRange']
			curParam = strategy[strategy_name]['curParam']
			for param_name in strategy_order['paramNameListDict'][strategy_name]:
				curParamIndex += 1
				if curParamIndex >= allParamIndex:
					# range-low任务完成，有效得到next，返回True
					return True
				strategy[strategy_name]['curParam'][param_name] = paramRange[param_name][0][0]

	# 把策略组参数重新置为初始（range-low）
	def resetParam(self, strategy):
		for strategy_name in strategy:
			paramRange = strategy[strategy_name]["paramRange"]
			curParam = strategy[strategy_name]["curParam"]
			for param_name, param in curParam.items():
				strategy[strategy_name]["curParam"][param_name] = paramRange[param_name][0][0]
	
	# 打印策略组的参数名
	# hongSanBing.item_len,...
	def printStrategyNames(self, strategy, strategy_order):
		name_list = []
		for strategy_name in strategy_order['nameList']:
			for param_name in strategy_order['paramNameListDict'][strategy_name]:
				name_list.append(strategy_name + "." + param_name)
		return ",".join(name_list)

	# 打印策略组的参数值
	# 3,1.3,2.55,...
	def printStrategyParams(self, strategy, strategy_order):
		value_list = []
		for strategy_name in strategy_order['nameList']:
			curParam = strategy[strategy_name]['curParam']
			for param_name in strategy_order['paramNameListDict'][strategy_name]:
				param_name_cur = curParam[param_name]
				value_list.append(param_name_cur)
		return ",".join([str(i) for i in value_list])
	
	# 打印m买卖所有策略组的参数名
	def printBuySellStrategyNames(self, buy_strategy, sell_strategy, buy_strategy_order, sell_strategy_order):
		buy_str = self.printStrategyNames(buy_strategy, buy_strategy_order)
		sell_str = self.printStrategyNames(sell_strategy, sell_strategy_order)
		return buy_str + "," + sell_str

	def printBuySellStrategyParams(self, buy_strategy, sell_strategy, buy_strategy_order, sell_strategy_order):
		buy_str = self.printStrategyParams(buy_strategy, buy_strategy_order)
		sell_str = self.printStrategyParams(sell_strategy, sell_strategy_order)
		return buy_str + "," + sell_str


	# 策略对于单股的详细表现
	# 收益采用close价格
	# 设计可统计历史策略交易状况的函数
	# 返回report_list[Dict{buytime，selltime，buy_price, sell_price, sellreasons，shouyi, related_shouyi(相对大盘收入)}]
	def strategyEvaluateDetail(self, itemDict, index_itemDict, sellDatetime_dict):
		report_list = []
		for buy_datetime, sell_info in sellDatetime_dict.items():
			sell_datetime = sell_info[0]
			sell_reason_list = sell_info[1]
			sell_reason_str = "-".join(sell_reason_list)
			buy_price = itemDict[buy_datetime][1]
			sell_price = itemDict[sell_datetime][1]
			# 大盘指数对应的买卖点
			# --有些个股在节假日有数据[误]，防止这些错误
			if index_itemDict.has_key(buy_datetime) and index_itemDict.has_key(sell_datetime):
				buy_index_value = index_itemDict[buy_datetime][1]
				sell_index_value = index_itemDict[sell_datetime][1]
			else:
				continue
			# 前复权会有负价，此时忽略不做统计
			if buy_price > 0.0 and sell_price > 0.0:
				shouyi = (sell_price - buy_price)/buy_price
				related_shouyi = shouyi - (sell_index_value - buy_index_value)/buy_index_value
			else:
				continue
			# dict KEY 为不可变内容，函数strategyEvaluateDetail，strategyEvaluateSummary会使用到
			trade_info = {"buy_datetime":buy_datetime, "sell_datetime":sell_datetime, "buy_price":buy_price, "sell_price":sell_price,\
						  "sell_reason_str":sell_reason_str, "shouyi":shouyi, "related_shouyi":related_shouyi}
			report_list.append(trade_info)
		return report_list

	# 从strategyEvaluateDetail函数返回结果，构造csv_str
	def getStrFromStrategyEvaluateDetail(self, code, report_list, detail_items=[]):
		all_str_list = []
		for one_trade in report_list:
			line_item_str_list = []
			for detail_item in detail_items:
				line_item_str = one_trade[detail_item]
				# 皆转换成str
				try:
					line_item_str = str(line_item_str)
				except:
					pass
				line_item_str_list.append(line_item_str)
			all_str_list.append(code + "," + ",".join(line_item_str_list))
		all_str = "\n".join(all_str_list)
		if all_str_list != []:
			all_str += '\n'
		return all_str

	# 策略对于单股的总结表现
	# 总交易次数，平均收益，收益标准差，平均相对收益，最大亏损，胜率
	# tradeNum，shouyiAvg，shouyiStd，relaShouyiAvg, maxKuisun, yingliPer
	def strategyEvaluateSummary(self, report_list, summary_items=["tradeNum","shouyiAvg"]):
		shouyi_list = []
		relaShouyi_list = []
		tradeNum = 0
		shouyiAvg = 0.0
		shouyiStd = 0.0
		relaShouyiAvg = 0.0
		maxKuisun = 0.0
		yingliNum = 0
		# -1.0表示没有交易次数，无胜率概念
		yingliPer = -1.0
		for trade_info in report_list:
			shouyi_list.append(trade_info["shouyi"])
			if trade_info["shouyi"] > 0.0:
				yingliNum += 1
			relaShouyi_list.append(trade_info["related_shouyi"])
			tradeNum += 1
		if tradeNum > 0:
			shouyiAvg = sum(shouyi_list)/tradeNum
			relaShouyiAvg = sum(relaShouyi_list)/tradeNum
			maxKuisun = min(shouyi_list)
			shouyiStd = numpy.std(shouyi_list, ddof=0)
			yingliPer = 1.0 * yingliNum / tradeNum
		# 只返回所需的评价指标
		summary_dict = {}
		if "tradeNum" in summary_items:
			summary_dict["tradeNum"] = tradeNum
		if "shouyiAvg" in summary_items:
			summary_dict["shouyiAvg"] = shouyiAvg
		if "shouyiStd" in summary_items:
			summary_dict["shouyiStd"] = shouyiStd
		if "relaShouyiAvg" in summary_items:
			summary_dict["relaShouyiAvg"] = relaShouyiAvg
		if "maxKuisun" in summary_items:
			summary_dict["maxKuisun"] = maxKuisun
		if "yingliPer" in summary_items:
			summary_dict["yingliPer"] = yingliPer
		# 组合成csv字串
		csv_str_list = []
		for summary_item in summary_items:
			csv_str_list.append(str(summary_dict[summary_item]))
		summary_csv_str = ",".join(csv_str_list)
		return summary_dict, summary_csv_str

		

	# 卖出时间点就近原则
	# 返回sell_dict[buyDatetime] = [sell_datetime, sell_reason_list]
	def getNearbySellDatetimeDict(self, datetimeDict_list):
		sell_dict = {}
		for datetimeDict in datetimeDict_list:
			for buy_datetime, sell_info in datetimeDict.items():
				sell_datetime = sell_info[0]
				sell_reason = sell_info[1]
				if not sell_dict.has_key(buy_datetime):
					sell_dict[buy_datetime] = [sell_datetime, [sell_reason]]
					continue
				old_sell_datetime = sell_dict[buy_datetime][0]
				# 卖出点一样，叠加理由
				if old_sell_datetime == sell_datetime:
					sell_dict[buy_datetime][1].append(sell_reason)
				# 更新卖出点，重置理由list
				elif old_sell_datetime > sell_datetime:
					sell_dict[buy_datetime][0] = sell_datetime
					sell_dict[buy_datetime][1] = [sell_reason]
				else:
					continue
		return sell_dict
				
	# 输入myfileInfo，输出myfileN.txt
	def nextFileName(self, filenameInfo, path):
		if path[-1] != '/':
			path += '/'
		filename_list = os.listdir(path)
		filename_pre = filenameInfo[0]
		filename_post = filenameInfo[1]
		Nmax = 0
		for filename in filename_list:
			# 忽略非文件
			if not os.path.isfile(path + filename):
				continue
			# 前后缀匹配
			if filename.find(filename_pre) == 0 and filename.find(filename_post) >= 0:
				# 获取前后缀中间内容
				N_str = filename[len(filename_pre):-(len(filename_post) + 1)]
				try:
					N = int(N_str)
				except:
					# 中间内容不是数字的，可能是其他文件，忽略
					continue
				if N > Nmax:
					Nmax = N
		return filename_pre + str(Nmax+1) + '.' + filename_post

	# 获取设定策略的指定日选股
	def SelectCurStock(self, curDate="2017-04-19 00:00:00"):
		StockObj = StockTool()
		ExrightsObj = ExrightsTool()
		flag, codes = StockObj.get_all_stock_code('all')
		if flag is False:
			print "get codes error"
		# ========策略设置=======
		data_period = [None, None]
		summary_period = [curDate, curDate]
		adj_mod = "pre"
		daymin = "day"
		# 长阳包阴策略
		'''
		buy_names=["yinBaoYang"]
		param_dict={'pingTai':{"item_len":10,"volat":0.2},\
					'warmUpShoot':{"warmDays":5,"ma_days":20,"KlenMin":0.08,"volSurpass":0.5,"maDiff":0.01,"StartMaPos":0.5},\
					'priceVolCoor':{"item_len":7,"vol_ma_days":5,"indexMin":0.2,"indexMax":9.9},\
					'redGreenRatio':{"item_len":20,"ratioMin":0.55,"ratioMax":1.0},\
					'pricePos':{"historyAll":1,"item_len":10,"posPercentMin":0.00,"posPercentMax":0.35},\
					'priceVolMaUp':{"subItem":2,"ma_days":20},\
					'yinBaoYang':{"yinPCR":0.2,"yangPCR":0.3},\
					}
		'''
		# 低位量价配合策略,20/5止盈，8止损，持20天
		'''
		buy_names=["priceVolCoor", "pricePos", "priceVolMaUp", "redGreenRatio"]
		param_dict={"priceVolCoor":{"item_len":30,"vol_ma_days":10,"indexMin":0.0,"indexMax":9.9},\
					"pricePos":{"historyAll":1,"item_len":10,"posPercentMin":0.00,"posPercentMax":0.4},\
					"priceVolMaUp":{"subItem":2,"ma_days":15},\
					"redGreenRatio":{"item_len":40,"ratioMin":0.7,"ratioMax":1.0}
					}
		'''
		# 低位量价配合，kdj地位金叉，,20/5止盈，8止损，持3天
		buy_names=['KDJGoldCross','priceVolCoor','pricePos']
		param_dict = {'priceVolCoor':{"item_len":10,"vol_ma_days":5,"indexMin":0.1,"indexMax":9.9},\
					  'pricePos':{"historyAll":1,"item_len":10,"posPercentMin":0.0,"posPercentMax":0.4},\
					  'KDJGoldCross':{"KDpos":0.4,"periodN":9,"KsmaN":3,"DsmaN":3},\
					}
		# 斗K策略
		'''
		buy_names=['ma3duoTouPaiLie', 'RedAndVolBig']
		param_dict = {'ma3duoTouPaiLie':{"ma1":5,"ma2":10,"ma3":20},\
					  'RedAndVolBig':{"volma1":5,"volma2":10,"greenDays":3, 'redLenth':0.03}}
		'''
		# ======策略设置结束=====
		buy_codes = []
		for code in codes:
			print "process code:%s"%code
			flag, itemList = ExrightsObj.getAdjItemList(code, adj_mod, daymin, data_period[0], data_period[1])
			if flag is False:
				print "[error] Get AdjItemList Failed, Code:%s"%code
				continue
			buyDatetime_set_list = []
			for strategy_name in buy_names:
				param_dict[strategy_name]['itemList'] = itemList
				param_dict[strategy_name]['period'] = summary_period
				datetimeList = self.runRecog(strategy_name, param_dict[strategy_name])
				buyDatetime_set_list.append(set(datetimeList))
			# 不同子策略取交集
			buyDatetime_set_jiao = buyDatetime_set_list[0]
			for buyDatetime_set in buyDatetime_set_list[1:]:
				buyDatetime_set_jiao = buyDatetime_set_jiao & buyDatetime_set
			buyDatetime_list = list(buyDatetime_set_jiao)
			if len(buyDatetime_list) <> 0:
				print "Buy code:%s"%code
				buy_codes.append(code)
		print buy_codes

	# 自顶向下优化策略组合和其参数，调用子函数OneStrategySummary()
	def StrategySearch(self, ):
		StockObj = StockTool()
		codes = StockObj.get_all_stock_code('all')[1]
		codes = ["600706"]
		strategy_result = self.OneStrategySummary(\
			codes=codes, \
			summary_csv=True, \
			detail_csv=True, \
			buy_names=['KDJGoldCross','priceVolCoor','pricePos'],\
			summary_period=['2015-01-01 00:00:00', None])
		
		

	# 自顶向下优化策略参数
	# 首先生成code_itemList数据，一直保存到训练结束
	# 固定参数下的策略表现，遍历code，并统计详细结果写到文件中
	# 遍历参数（可暴力，可粒子群等算法），重复上述步骤
	def OneStrategySummary(self, \
			# =========================参数=========================
			report_csvfile_info=["report", "csv"], \
			# 设定交易细节内容（保存到csv）
			trade_detail_items = ["buy_datetime","sell_datetime","buy_price","sell_price","sell_reason_str","shouyi","related_shouyi"],\
			# 设定评价指标
			# 限定以下["tradeNum","shouyiAvg","shouyiStd","relaShouyiAvg", "maxKuisun"]
			# 限定动作由函数strategyEvaluateSummary发出
			summary_items = ["tradeNum","shouyiAvg","shouyiStd","relaShouyiAvg", "maxKuisun", "yingliPer"],\
			# 数据背景设置
			codes = ["300033", "600000"],\
			relate_index = '000001',\
			data_period = [None, None],\
			summary_period = ["2013-01-01 00:00:00",None],\
			adj_mod = "pre",\
			daymin = "day",\
			# 策略框架设置，暂不支持同recogFunc在同一个买或卖策略组内
			buy_names=["priceVolCoor","pricePos","priceVolMaUp","redGreenRatio"],\
			sell_names=["zhiYingSun"],\
			paramLimit={'buy':{\
						   'pingTai':{"item_len":[[10,20],10],"volat":[[0.10,0.20],0.05]},\
						   'warmUpShoot':{"warmDays":[[2,10],1],"ma_days":[[20,20],1],"KlenMin":[[0.07,0.1],0.01],\
										"volSurpass":[[0.3,0.5],0.1],"maDiff":[[0.01,0.02],0.01],"StartMaPos":[[0.1,0.5],0.1]},\
						   'priceVolCoor':{"item_len":[[10,20],5],"vol_ma_days":[[5,10],5],"indexMin":[[0.00,0.30],0.1],"indexMax":[[9.9,9.9],0.1]},\
						   'redGreenRatio':{"item_len":[[30,60],20],"ratioMin":[[0.6,0.6],0.1],"ratioMax":[[1.0,1.0],0.1]},\
						   'pricePos':{"historyAll":[[1,1],1],"item_len":[[10,10],10],"posPercentMin":[[0.0,0.0],0.05],\
									   "posPercentMax":[[0.3,0.5],0.1]},\
						   'priceVolMaUp':{"subItem":[[2,2],1],"ma_days":[[5,20],5]},\
						   'KDJGoldCross':{"KDpos":[[0.4,0.4],0.1],"periodN":[[9,9],1],"KsmaN":[[3,3],1],"DsmaN":[[3,3],1]},\
						   'ma3tuoDuoPaiLie':{"ma1":[[5,5],1],"ma2":[[10,10],1],"ma3":[[20,20],1]},\
						   "RedAndVolBig":{"redLenth":[[0.03,0.03],0.01],"volma1":[[5,5],1],"volma2":[[10,10],1],"greenDays":[[3,3],1]},\
						  },\
						'sell':{"zhiYingSun":{"MaxYingliPercent":[[0.2,0.2],0.1],"YingliHuiLuo":[[0.05,0.05],0.01],"zhiSun":[[0.08,0.08],0.02],\
										  "holdday_max":[[1,10],1],"holdtoday":[[0,0],1]}}
					   },\
			detail_csv=False,
			summary_csv=False
	):
		ExrightsObj = ExrightsTool()
		BasicObj = BasicTool()
		report_csvfile = self.nextFileName(report_csvfile_info, './')
		return_dict = {}
		# 基本数据获取
		code_itemList = {}
		code_itemDict = {}
		i = 0
		for code in codes:
			i+=1
			print i
			flag, itemList = ExrightsObj.getAdjItemList(code, adj_mod, daymin, data_period[0], data_period[1])
			if flag is False:
				return False, itemList
			code_itemList[code] = itemList
			code_itemDict[code] = BasicObj.tran2Dict(itemList)
		# --大盘数据获取
		flag, index_itemList = BasicObj.getOriItemList(relate_index, True, daymin, data_period[0], data_period[1])
		if flag is False:
			return False, index_itemList
		index_itemDict = BasicObj.tran2Dict(index_itemList)
		# 策略结构获取
		buy_strategy, sell_strategy, buy_strategy_order, sell_strategy_order = self.createStratey(buy_names, sell_names, paramLimit)
		# 遍历策略参数
		csv_head_strategy_part = self.printBuySellStrategyNames(buy_strategy, sell_strategy, buy_strategy_order, sell_strategy_order)
		print csv_head_strategy_part
		return_dict["param_name_str"] = csv_head_strategy_part
		return_dict["summary"] = {}
		# 创建csv文件的头部
		if summary_csv is True:
			f = open(report_csvfile, "a+")
			f.write(",".join([csv_head_strategy_part, ",".join(summary_items)])+'\n')
			f.close()
		if detail_csv is True:
			f = open(report_csvfile+"_detail", "a+")
			f.write("code" + "," + ",".join(trade_detail_items) + '\n')
			f.close()
		while True:
			while True:
				# =======使用buy_strategy, sell_strategy固定参数，对各个code统计效果=======
				csv_body_strategy_part = self.printBuySellStrategyParams(buy_strategy, sell_strategy, buy_strategy_order, sell_strategy_order)
				print csv_body_strategy_part
				if detail_csv is True:
					f = open(report_csvfile+"_detail", "a+")
					f.write(csv_body_strategy_part+'\n')
					f.close()
				allCodeTradeDetail = []
				# --遍历code
				for code in codes:
					# 计算买入时刻及理由
					buyDatetime_set_list = []
					#print 'cal buy datetime'
					for strategy_name, strategy_info in buy_strategy.items():
						param_dict = copy.deepcopy(strategy_info['curParam'])
						param_dict['itemList'] = code_itemList[code]
						param_dict['period'] = summary_period
						datetimeList = self.runRecog(strategy_name, param_dict)
						#print strategy_name
						#print datetimeList
						buyDatetime_set_list.append(set(datetimeList))
					# 不同子策略取交集
					buyDatetime_set_jiao = buyDatetime_set_list[0]
					for buyDatetime_set in buyDatetime_set_list[1:]:
						buyDatetime_set_jiao = buyDatetime_set_jiao & buyDatetime_set
					buyDatetime_list = list(buyDatetime_set_jiao)
					#print 'cal buy datetime jiaoji'
					#print buyDatetime_list
					# 计算卖出时刻及理由
					#print 'cal sell datetime'
					datetimeDict_list = []
					for strategy_name, strategy_info in sell_strategy.items():
						param_dict = copy.deepcopy(strategy_info['curParam'])
						param_dict['itemList'] = code_itemList[code]
						param_dict['period'] = summary_period
						param_dict['buyDatetime_list'] = buyDatetime_list
						datetimeDict = self.runRecog(strategy_name, param_dict)
						#print strategy_name
						#print datetimeDict
						datetimeDict_list.append(datetimeDict)
					# 不同卖出策略就近原则
					sellDatetime_dict = self.getNearbySellDatetimeDict(datetimeDict_list)
					# 统计该策略该股票的历史效果
					tradeDetail = self.strategyEvaluateDetail(code_itemDict[code], index_itemDict, sellDatetime_dict)
					codeReport = self.strategyEvaluateSummary(tradeDetail, summary_items)
					allCodeTradeDetail += tradeDetail
					# ----统计单股结果
					#print tradeDetail
					#print codeReport
					if detail_csv is True:
						f = open(report_csvfile+"_detail", "a+")
						f.write(self.getStrFromStrategyEvaluateDetail(code, tradeDetail, trade_detail_items))
						f.close()
				# -----统计该策略下所有个股的历史效果
				allCodeReportDict, summary_csv_str = self.strategyEvaluateSummary(allCodeTradeDetail, summary_items)
				print allCodeReportDict
				return_dict["summary"][csv_body_strategy_part] = allCodeReportDict
				if summary_csv is True:
					f = open(report_csvfile, "a+")
					f.write(",".join([csv_body_strategy_part, summary_csv_str])+'\n')
					f.close()
				# =========================================================================
				if not self.nextParam(sell_strategy, sell_strategy_order):
					self.resetParam(sell_strategy)
					break
			if not self.nextParam(buy_strategy, buy_strategy_order):
				break
		return return_dict


if __name__ == '__main__':
	obj = Strategy()
	#obj.OneStrategySummary()
	#obj.StrategySearch()
	obj.SelectCurStock()
